/**
 * 
 */
package com.qq.spirit;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import com.qq.spirit.CampaignTask.Campaign;
import com.qq.spirit.inter.AbstractXmlActionAfterRequest;
import com.qq.spirit.inter.TaskUnit;
import com.qq.spirit.model.UserData;
import com.qq.spirit.model.XmlDataUtil;
import com.qq.spirit.model.XmlNodeData;

/**
 * 军团征战
 * 
 * @author beedoorwei
 * 
 */
public class BattleMultiTask extends TaskUnit
{
	public BattleMultiTask()
	{
		this.taskDesc = "军团征战";
	}

	@Override
	public void doTask()
	{
		try
		{
			if (!GameUserInfoUtil.getIsUserLoadSuc())
			{
				TaskManager.addTask(this, 10);
			} else
			{
				Iterator<Integer> ite = GameUserInfoUtil.userIte();
				while (ite.hasNext())
				{
					int gid = ite.next();
					UserData u = GameUserInfoUtil.getUser(gid);
					if (u.getConfigValue("openBattle", "0").equals("1"))
					{
						TaskManager.addTask(new BattleMulti(gid), GameUtil.randomInt(10));
					}
				}
			}
		} catch (Exception e)
		{
			LoggerUtil.error(0, e);
		}
	}

	/**
	 * 获得下次可攻击的时间
	 * 
	 * @return
	 */
	private int getNextAttackTime(Integer gid)
	{
		int attackTime = 0;
		Calendar cl = Calendar.getInstance();
		int hour = cl.get(Calendar.HOUR_OF_DAY);
		if (hour >= 0 && hour < 13)
		{
			long curr = cl.getTimeInMillis();
			cl.set(Calendar.HOUR_OF_DAY, 13);
			cl.set(Calendar.MINUTE, 0);
			cl.set(Calendar.SECOND, 0);
			long next = cl.getTimeInMillis();
			attackTime = (int) ((next - curr) / 1000 + 1);
		} else if (hour >= 13 && hour < 14)
		{
			attackTime = 0;
		} else if (hour >= 14 && hour < 20)
		{
			long curr = cl.getTimeInMillis();
			cl.set(Calendar.HOUR_OF_DAY, 20);
			cl.set(Calendar.MINUTE, 0);
			cl.set(Calendar.SECOND, 0);
			long next = cl.getTimeInMillis();
			attackTime = (int) ((next - curr) / 1000 + 1);
		} else if (hour >= 20 && hour < 23)
		{
			attackTime = 0;
		} else if (hour >= 23 && hour < 24)
		{
			long curr = cl.getTimeInMillis();
			cl.add(Calendar.DAY_OF_MONTH, 1);
			cl.set(Calendar.HOUR_OF_DAY, 13);
			cl.set(Calendar.MINUTE, 0);
			cl.set(Calendar.SECOND, 0);
			long next = cl.getTimeInMillis();
			attackTime = (int) ((next - curr) / 1000 + 1);
		}

		if (attackTime == 0)
		{
			String tokencd = XmlDataUtil.getNodeData(GameUserInfoUtil.getUser(gid).getAllPlayInfo(), "results.player.tokencd");
			int nextattack = GameUtil.convertInt(tokencd);
			if (nextattack >= (25 * 60 * 1000))
			{
				// 休息5分钟
				attackTime = 5 * 60;
			}
		}
		return 0;
		// return attackTime;
	}

	/**
	 * 判断是否可以攻击
	 * 
	 * @param battleMultiInfo
	 * @return
	 */
	private boolean isCanBattleMultiAttack(Integer gid)
	{
		// 判断能够发动攻击的最快时间
		int nextAttackTime = getNextAttackTime(gid);
		if (nextAttackTime > 0)
		{
			TaskManager.addTask(new BattleMulti(gid), nextAttackTime);
			return false;
		}
		String times = XmlDataUtil.getNodeData(GameUserInfoUtil.getUser(gid).getAllPlayInfo(), "results.player.token");
		if (GameUtil.convertInt(times) >= 0)
		{
			return true;
		}
		return false;
	}

	/**
	 * 军团征战
	 * 
	 * @author Administrator
	 * 
	 */
	class BattleMulti extends TaskUnit
	{
		public BattleMulti(Integer gid)
		{
			this.gid = gid;
		}

		public void doTask()
		{
			try
			{
				UserData u = GameUserInfoUtil.getUser(gid);
				if (u.getUserState() == UserState.LOGIN_GAME)
				{
					List<BasicNameValuePair> nvpList = new ArrayList<BasicNameValuePair>();
					// 目前默认水浒军团
					nvpList.add(new BasicNameValuePair("armiesId", u.getConfigValue("BattleArmId", "900023")));
					HttpUtil.doPost(gid, GameConstants.BATTLE_MULTI_VIEW_URL, nvpList, new PreBattleMultiAction(gid));
				} else
				{
					// 添加登录任务先
					TaskManager.addTask(new LoginTask(gid, this));
				}
			} catch (Exception e)
			{
				LoggerUtil.error(gid,e);
			}
		}
	}

	/**
	 * 征战前查询
	 * 
	 * @author Administrator
	 * 
	 */
	class PreBattleMultiAction extends AbstractXmlActionAfterRequest
	{
		public PreBattleMultiAction(Integer gid)
		{
			super();
			this.gid = gid;
			this.taskUnit = new BattleMulti(gid);
		}

		public void doCall(List<Header> headerList, XmlNodeData battleMultiInfo)
		{
			doBattleMulti(battleMultiInfo);
		}

		/**
		 * 获取本国组队
		 * 
		 * @param battleMultiInfo
		 * @return
		 */
		private List<XmlNodeData> searchNationTeam(XmlNodeData battleMultiInfo)
		{
			UserData u = GameUserInfoUtil.getUser(gid);
			String usernation = GameUtil.getNation(u.getGameInfo("nation"));
			List<XmlNodeData> tempNode = XmlDataUtil.getNodeInfoList(battleMultiInfo, "results.team.condition");
			List<XmlNodeData> nationTeamList = new ArrayList<XmlNodeData>();
			if (!tempNode.isEmpty())
			{
				// 不为空，有组队，查查是否有本国籍的队伍
				for (XmlNodeData cn : tempNode)
				{
					if (cn.getNodeValue().indexOf(usernation) >= 0)
					{
						nationTeamList.add(cn.getParent());
					}
				}
			}
			return nationTeamList;
		}

		/**
		 * 判断是否为队长
		 * 
		 * @param nationTeamList
		 * @return
		 */
		private boolean isTeamLeader(List<XmlNodeData> nationTeamList)
		{
			for (XmlNodeData xm : nationTeamList)
			{
				String teamname = XmlDataUtil.getNodeData(xm, "teamname");
				if (teamname.equals(GameUserInfoUtil.getGameName(gid)))
				{
					return true;
				}
			}
			return false;
		}

		/**
		 * 是否在组队中
		 * 
		 * @param battleMultiInfo
		 * @return
		 */
		private boolean isInTeam(XmlNodeData battleMultiInfo)
		{
			List<XmlNodeData> tempNode = XmlDataUtil.getNodeInfoList(battleMultiInfo, "results.member.playername");
			for (XmlNodeData xm : tempNode)
			{
				if (xm.getNodeValue().equals(GameUserInfoUtil.getGameName(gid)))
				{
					return true;
				}
			}

			return false;
		}

		/**
		 * @param battleMultiInfo
		 * @return
		 */
		private int getTeamCurrNum(List<XmlNodeData> nationTeamList)
		{
			for (XmlNodeData xm : nationTeamList)
			{
				String teamname = XmlDataUtil.getNodeData(xm, "teamname");
				if (teamname.equals(GameUserInfoUtil.getGameName(gid)))
				{
					return GameUtil.convertInt(XmlDataUtil.getNodeData(xm, "currentnum"));
				}
			}
			return 0;
		}

		/**
		 * 开始军团
		 */
		private void doBattleMulti(XmlNodeData battleMultiInfo)
		{
			UserData u = GameUserInfoUtil.getUser(gid);
			List<XmlNodeData> nationTeamList = searchNationTeam(battleMultiInfo);
			if (nationTeamList.isEmpty())
			{
				LoggerUtil.logger(gid,"没有查询到本国组队信息");
				createTeam(u.getConfigValue("BattleArmId", "900023"));
			} else
			{
				// 有组队，分2步，先看看自己是否是队长，如果不是，判断是否在队伍中
				if (isTeamLeader(nationTeamList))
				{
					// 找到了，那么这个号就是队长，查看人数是否满足条件
					int currentnum = getTeamCurrNum(nationTeamList);
					if (currentnum >= 5)
					{
						// 开始吧
						HttpUtil.doGet(gid, GameConstants.BATTLE_MULTI_ATTACK_URL, new BattleMultiAttackAction(gid));
					} else
					{
						// 继续等待，5秒钟后继续看
						TaskManager.addTask(new BattleMulti(gid), GameUtil.randomInt(10));
					}
				} else
				{
					// 没找到，看看自己是否是队员
					if (isInTeam(battleMultiInfo))
					{
						// 等待5秒钟后再看下组队信息
						TaskManager.addTask(new BattleMulti(gid), 5);
					} else
					{
						joinOrCreateTeam(nationTeamList);
					}
				}
			}
		}

		/**
		 * 开启加入组队/创建组队功能，优先加入组队，如果没队伍可以加，那么就创建组队
		 */
		private void joinOrCreateTeam(List<XmlNodeData> nationTeamList)
		{
			XmlNodeData tp = null;
			Iterator<XmlNodeData> teamIte = nationTeamList.iterator();
			while (teamIte.hasNext())
			{
				tp = teamIte.next();
				int currentnum = GameUtil.convertInt(XmlDataUtil.getNodeData(tp, "currentnum"));
				if (currentnum < 8)
				{
					teamIte.remove();
					break;
				}
			}
			if (tp != null)
			{
				// 找到了小于8个人的组队
				List<NameValuePair> nvpList = new ArrayList<NameValuePair>();
				nvpList.add(new NameValuePair("teamId", XmlDataUtil.getNodeData(tp, "teamid")));
				HttpUtil.doPost(gid, GameConstants.BATTLE_MULTI_JOIN_TEAM_URL, nvpList, new BattleMultiJoinTeamAction(gid, nationTeamList));
			} else
			{
				createTeam();
			}
		}

		/**
		 * 创建组队
		 */
		private void createTeam(String armId)
		{
			List<BasicNameValuePair> nvpList = new ArrayList<BasicNameValuePair>();
			nvpList.add(new BasicNameValuePair("armiesId", armId));
			nvpList.add(new BasicNameValuePair("rule", "4:0;2"));
			HttpUtil.doPost(gid, GameConstants.BATTLE_MULTI_CREATE_TEAM_URL, nvpList, new BattleMultiTeamAction(gid));
		}

	}

	/**
	 * 发起攻击事后处理对象
	 * 
	 * @author Administrator
	 * 
	 */
	class BattleMultiAttackAction extends AbstractXmlActionAfterRequest
	{
		public BattleMultiAttackAction(Integer gid)
		{
			super();
			this.gid = gid;
			this.taskUnit = new BattleMulti(gid);
		}

		@Override
		public void doCall(List<NameValuePair> headerList, XmlNodeData battleMultiAttackInfo)
		{
			// 获取攻击结果
			String describe = XmlDataUtil.getNodeData(battleMultiAttackInfo, "results.sceneevent.battlereport.report.describe");
			String gains = XmlDataUtil.getNodeData(battleMultiAttackInfo, "results.sceneevent.battlereport.report.gains");
			LoggerUtil.info(GameUserInfoUtil.getGameName(gid) + "攻击军团:" + describe + "," + GameUtil.getStr(gains));

			String token = XmlDataUtil.getNodeData(battleMultiAttackInfo, "results.sceneevent.playerbattleinfo.token");
			String tokencd = XmlDataUtil.getNodeData(battleMultiAttackInfo, "results.sceneevent.playerbattleinfo.tokencd");
			GameUserInfoUtil.getUser(gid).getAllPlayInfo().setValue("results.player.token", token);
			GameUserInfoUtil.getUser(gid).getAllPlayInfo().setValue("results.player.tokencd", tokencd);

			// 提交5秒钟后刷新
			TaskManager.addTask(new BattleMulti(gid), GameUtil.randomInt(10));
		}
	}

	/**
	 * 创建组队回调事件
	 * 
	 * @author Administrator
	 * 
	 */
	class BattleMultiTeamAction extends AbstractXmlActionAfterRequest
	{
		public BattleMultiTeamAction(Integer gid)
		{
			super();
			this.gid = gid;
			this.taskUnit = new BattleMulti(gid);
		}

		@Override
		public void doCall(List<Header> headerList, XmlNodeData battleMultiInfo)
		{
			String createBattleMultiTeamResult = GameUtil.getResultState(battleMultiInfo);
			if (createBattleMultiTeamResult.equals("1"))
			{
				// 创建组队成功
				LoggerUtil.info(gid,GameUserInfoUtil.getGameName(gid) + "创建军团组队成功");
			} else
			{
				String message = GameUtil.getResultMessage(battleMultiInfo);
				// 创建组队失败
				LoggerUtil.info(gid,GameUserInfoUtil.getGameName(gid) + "创建军团组队失败，原因:" + message);
			}
			// 提交5秒钟后刷新任务,如果成功刷新等待开始攻击，否则重新征战任务
			TaskManager.addTask(new BattleMulti(gid), GameUtil.randomInt(10));
		}
	}

	/**
	 * 加入组队回调事件
	 * 
	 * @author Administrator
	 * 
	 */
	class BattleMultiJoinTeamAction extends AbstractXmlActionAfterRequest
	{
		List<XmlNodeData> nationTeamList = null;

		public BattleMultiJoinTeamAction(Integer gid, List<XmlNodeData> nationTeamList)
		{
			super();
			this.gid = gid;
			this.taskUnit = new BattleMulti(gid);
		}

		public void doCall(List<NameValuePair> headerList, XmlNodeData battleMultiInfo)
		{
			String createBattleMultiTeamResult = GameUtil.getResultState(battleMultiInfo);
			if (createBattleMultiTeamResult.equals("1"))
			{
				// 加入组队成功
				LoggerUtil.info(GameUserInfoUtil.getGameName(gid) + "加入军团组队成功");
				// 提交5秒钟后,战役结果任务
				HttpUtil.doGet(gid, GameConstants.BATTLE_MULTI_ATTACK_URL, new BattleMultiResultAction(gid));
			} else
			{
				String message = GameUtil.getResultMessage(battleMultiInfo);
				// 加入组队失败
				LoggerUtil.info(GameUserInfoUtil.getGameName(gid) + "加入军团组队失败，原因:" + message);
				// 失败后，重新执行军团组队任务
				TaskManager.addTask(new BattleMulti(gid), GameUtil.randomInt(10));
			}
		}
	}

	/**
	 * 战役结果任务
	 * 
	 * @author beedoorwei
	 * 
	 */
	class BattleMultiResultAction extends AbstractXmlActionAfterRequest
	{
		public BattleMultiResultAction(Integer gid)
		{
			super();
			this.gid = gid;
			this.taskUnit = new BattleMulti(gid);
		}

		public void doCall(List<NameValuePair> headerList, XmlNodeData battleMultiInfo)
		{

		}
	}
}
